/*
 * Copyright (C) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef REMOTE_DEATH_MANAGER_H
#define REMOTE_DEATH_MANAGER_H

#include <functional>
#include <map>
#include <mutex>
#include <tuple>
#include "refbase.h"
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "wifi_log.h"

namespace OHOS {
namespace Wifi {
template <typename T, typename Y>
class RemoteDeathNanager final {
public:
    using RemoteDeathMap = std::map<sptr<T>, sptr<Y>>;
    RemoteDeathNanager() = default;
    ~RemoteDeathNanager();
    bool Register(const sptr<T> &observer);
    bool Deregister(const sptr<IRemoteObject> &observer);
    void DeregisterAll();
    RemoteDeathNanager(const RemoteDeathNanager &) = delete;
    RemoteDeathNanager &operator=(const RemoteDeathNanager &) = delete;

private:
    bool UnregisterInternal(typename RemoteDeathMap::iterator iter);
private:
    std::mutex lock_ {};
    RemoteDeathMap remoteDeaths_ {};
};

template <typename T, typename Y>
RemoteDeathNanager<T, Y>::~RemoteDeathNanager()
{
    LOGD("RemoteDeathNanager<T, Args...>::~RemoteDeathNanager() called");
    std::lock_guard<std::mutex> lock(lock_);
    for (auto it = remoteDeaths_.begin(); it != remoteDeaths_.end(); ++it) {
        sptr<T> rt = it->first;
        sptr<Y> dr = it->second;
        if (!rt->AsObject()->RemoveDeathRecipient(dr)) {
            LOGE("Failed to unlink death recipient from observer");
        }
    }
    remoteDeaths_.clear();
}

template <typename T, typename Y>
bool RemoteDeathNanager<T, Y>::Register(const sptr<T> &callback)
{
    LOGD("RemoteDeathNanager<T, Y>::Register called");
    std::lock_guard<std::mutex> lock(lock_);
    bool isMatch = false;
    for (const auto &it : remoteDeaths_) {
        if (it.first != nullptr && it.first->AsObject() == callback->AsObject()) {
            LOGE("callback map already contains given observer");
            isMatch = true;
            break;
        }
    }
    if (!isMatch) {
        sptr<Y> dr(new (std::nothrow) Y(this));
        if (!callback->AsObject()->AddDeathRecipient(dr)) {
            LOGE("Failed to link death recipient to callback");
        }
        remoteDeaths_[callback] = dr;
    }
    return true;
}

template <typename T, typename Y>
bool RemoteDeathNanager<T, Y>::Deregister(const sptr<IRemoteObject> &remote)
{
    LOGD("RemoteDeathNanager<T, Y>::Deregister called");
    std::lock_guard<std::mutex> lock(lock_);
    for (auto it = remoteDeaths_.begin(); it != remoteDeaths_.end();) {
        if (it->first != nullptr && it->first->AsObject() == remote) {
            UnregisterInternal(it++);
        } else {
            it++;
        }
    }
    return true;
}

template <typename T, typename Y>
void RemoteDeathNanager<T, Y>::DeregisterAll()
{
    LOGD("RemoteDeathNanager<T, Y>::Deregister called");
    std::lock_guard<std::mutex> lock(lock_);
    for (auto it = remoteDeaths_.begin(); it != remoteDeaths_.end();) {
        UnregisterInternal(it++);
    }
}

template <typename T, typename Y>
bool RemoteDeathNanager<T, Y>::UnregisterInternal(typename RemoteDeathMap::iterator iter)
{
    LOGD("RemoteObserverList<T, Y>::UnregisterInternal called");
    sptr<T> rt = iter->first;
    sptr<Y> dr = iter->second;
    if (!rt->AsObject()->RemoveDeathRecipient(dr)) {
        LOGE("Failed to unlink death recipient from callback");
    }
    remoteDeaths_.erase(iter);
    return true;
}
}  // namespace Wifi
}  // namespace OHOS
#endif  // REMOTE_DEATH_MANAGER_H
